package com.intelligy.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.intelligy.R
import com.intelligy.bean.Music

class MusicListViewMainAdapter(private val musics: List<Music>, private val context: Context) :
    BaseAdapter() {

    private val inflater: LayoutInflater = LayoutInflater.from(context)

    override fun getCount() = musics.size

    override fun getItem(position: Int) = musics[position]

    override fun getItemId(position: Int) = position.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view: View
        val holder: Holder
        if (convertView == null) {
            // 第一次调用getView()时，conVertView 时空的
            view = inflater.inflate(R.layout.list_item, null)

            // 将布局视图封装到对象中，方便层出
            holder = Holder(
                view.findViewById(R.id.txtv_main_list_item_singer),
                view.findViewById(R.id.txtv_main_list_item_title)
            )

            // 将视图存储起来，用于重复使用
            view.tag = holder
        } else {
            view = convertView
            // 从第二次开始，convertView 不在为空，切其tag值还附带了一个视图模板
            holder = convertView.tag as Holder
        }
        // 给视图上的元素设置数据
        holder.title.text = musics[position].title
        holder.singer.text = musics[position].singer

        // 最后返回这个视图，系统就会根据这个视图绘制到listview上
        return view
    }

    // 为了打包视图上的几个空间
    data class Holder(
        var singer: TextView,
        var title: TextView
    )

}
